from fastapi import APIRouter, HTTPException
from apps.users.models import User
from typing import List
from fastapi import Request
from apps.users.dataTemplate import UserIn, UserOut
from tortoise.exceptions import DoesNotExist
from logger_config import setup_logger

# 设置日志记录器
logger = setup_logger()

users = APIRouter()


# 获取用户列表
@users.get("/list", response_model=List[UserOut])
async def get_user_list():
    user_list = await User.all()
    return user_list


# 获取用户信息
@users.get("/{user_id}/info", response_model=UserOut)
async def get_user_info(user_id: int):
    try:
        user = await User.get(id=user_id)
        return user
    except DoesNotExist as e:
        logger.error(f"Error occurred while fetching User video info for user_id:{user_id}: {e}")
        raise HTTPException(status_code=404, detail="用户未找到")


# 编辑用户信息
@users.post("/{user_id}/edit", response_model=UserOut)
async def get_user_edit(user_id: int, user_in: UserIn):
    try:
        # 获取当前用户数据
        user = await User.get(id=user_id)

        # 更新用户数据
        user_data = user_in.model_dump(exclude_unset=True)  # 只更新传入的字段
        await User.filter(id=user_id).update(**user_data)

        # 返回更新后的用户信息
        updated_user = await User.get(id=user_id)
        return updated_user
    except DoesNotExist as e:
        logger.error(f"Error occurred while editing User video info for user_id:{user_id}: {e}")
        raise HTTPException(status_code=404, detail="用户未找到")


# 删除用户
@users.post("/{user_id}/delete")
async def delete_user(user_id: int):
    try:
        user = await User.get(id=user_id)
        await user.delete()
        return {"status": "success", "message": "用户已删除"}
    except DoesNotExist as e:
        logger.error(f"Error occurred while deleting User video info for user_id:{user_id}: {e}")
        raise HTTPException(status_code=404, detail="用户未找到")


# 添加新用户
@users.post("/add", response_model=UserOut)
async def add_user(user_in: UserIn):
    user_data = user_in.model_dump()
    user_data['crawl_count'] = 0
    user_data['groups_id'] = 3
    user = await User.create(**user_data)
    return user


# 搜索用户
@users.get("/search/{username}", response_model=List[UserOut])
async def search_user_by_username(username: str):
    users = await User.filter(username__icontains=username)
    if not users:
        raise HTTPException(status_code=404, detail="未找到匹配的用户")
    return users
